import 'package:fish_redux/fish_redux.dart';
import 'package:fish_redux/src/redux/basic.dart' as fish;
import 'action.dart';
import 'state.dart';
import 'package:flutter/material.dart';
import 'package:rss_readneed/punch_card/punchCardModel.dart';
import 'package:rss_readneed/punch_card/setting/page.dart' as setting;
import 'package:rss_readneed/punch_card/list/page.dart' as list;
import 'package:rss_readneed/public.dart';

import 'package:rss_readneed/sn_support/SNAccount.dart';

Effect<punch_cardState> buildEffect() {
  return combineEffects(<Object, Effect<punch_cardState>>{
    Lifecycle.initState:_initAction,
    Lifecycle.dispose:_dispose,
    punch_cardAction.showDatePickerAction: _showDatePickerAction,
    punch_cardAction.showTimePickerAction: _showTimePickerAction,
    punch_cardAction.punchCardAction:_punchCardAction,
    punch_cardAction.pushSettingVC:_pushSettingVC,
    punch_cardAction.pushListVC:_pushListVC,
    punch_cardAction.changeFirstPage:_changeFirstPage,

    Lifecycle.deactivate:_deactivate,
  });
}

void _initAction(fish.Action action, Context<punch_cardState> ctx) {

  if (ctx.state.isChange == false && ctx.state.isToday == true) {//如果不是修改，同时又是今天，校验是否有相关数据已存在

    //获取当天string
    String dateString = PunchCardModel().dateTimeString(PunchCardModel().todayDateTime());

    //然后用当天做匹配，万一存储的数据里面有则应该展示,数据更改和查询放在effect
    Future<List<PunchCardModel>> datas = PunchCardModel().getDatas();

    datas.then((List<PunchCardModel> list){

      if (list == null) return ;

      for (int i = 0;i < list.length; i++) {

        PunchCardModel model = list[i];

        if (model.dateTime == dateString) {//命中当天存在数据，则返回更新当天数据

          ctx.dispatch(punch_cardActionCreator.restartTodayAction({"isToday":true,"isChange":true,"model":model}));
          return ;
        }
      }
    });

  }

  //刷新今天要做的事 - 取值不做控制,展示控制(默认取值,展不展示由判断决定)
  PunchCardModel().getTomorrowThings().then((List<String> list){

    ctx.state.storeTomorrowThings = list;

    ctx.dispatch(punch_cardActionCreator.refreshTodayDoThings());
  });

  monthTotalInfo(ctx);

  PunchCardSettingModel.noti.stream.listen((_){

    monthTotalInfo(ctx);
  });
}

//push:deactivate->build 页面会进入不可用状态，并重新build(但不会绘制),A页面不会卸载。
//pop:deactivate->build 页面进入运行状态
void _deactivate(fish.Action action, Context<punch_cardState> ctx) async {

  String pageShortString = AppNavigator.instance.locationPageShortString;
  if (pageShortString.contains("/")) {

    //更新统计数据
    monthTotalInfo(ctx);

    //比对更新数据,在更新的数据集里面
    List<PunchCardModel> list = await PunchCardModel().getDatas();

    for (int i = 0;i < list.length; i++) {

      PunchCardModel model = list[i];

      if (model.dateTime == ctx.state.model.dateTime) {//命中存在数据，携带状态和时间返回，不改变已存在其他的信息

        PunchCardModel storeModel = PunchCardModel(
          yearTime: ctx.state.model.yearTime,
          monthTime: ctx.state.model.monthTime,
          dateTime: ctx.state.model.dateTime,
          todayThings: ctx.state.model.todayThings,
          finishTime: model.finishTime,
          workingThings: ctx.state.controller.text,
          tomorrowThings: ctx.state.model.tomorrowThings,
          inCount:model.inCount,
        );

        ctx.dispatch(punch_cardActionCreator.sureDatePickerAction({"isToday":PunchCardModel().isToday(model.dateTime),"isChange":true,"model":storeModel}));
        break ;
      }
    }
  }
}

void _dispose(fish.Action action, Context<punch_cardState> ctx) {

  ctx.state.scrollController.dispose();
  ctx.state.controller.dispose();

  for (int i = 0 ; i < ctx.state.tomorrowControllers.length ; i++ ) {

    TextEditingController controller = ctx.state.tomorrowControllers[i];
    controller.dispose();
  }
}

void _showDatePickerAction(fish.Action action, Context<punch_cardState> ctx) async {

  DateTime timeSelected = await showDatePicker(
    context: ctx.context,
    initialDate: DateTime.parse(ctx.state.model.dateTime),
    firstDate: DateTime(2000),
    lastDate: DateTime(2099),
  );

  if (timeSelected == null) return ;
  //转换成model的dateTime
  String dateString = PunchCardModel().dateTimeString(timeSelected);

  if (dateString == ctx.state.model.dateTime) {//当前选择的日期与正在编辑的相同

    return ;
  }

  monthTotalInfo(ctx);

  List<PunchCardModel> list = await PunchCardModel().getDatas();

  for (int i = 0;i < list.length; i++) {

    PunchCardModel model = list[i];

    if (model.dateTime == dateString) {//命中存在数据，携带数据返回

      ctx.dispatch(punch_cardActionCreator.sureDatePickerAction({"isToday":PunchCardModel().isToday(dateString),"isChange":true,"model":model}));
      return ;
    }
  }

  //没有数据或者没有命中
  bool isToday = PunchCardModel().isToday(dateString);

  PunchCardModel model = PunchCardModel().initModelWith(timeSelected);

  ctx.dispatch(punch_cardActionCreator.sureDatePickerAction({"isToday":isToday,"isChange":false,"model":model}));
}

void _showTimePickerAction(fish.Action action, Context<punch_cardState> ctx) async {

  //如果选择9点以前的时间将会自动移至下一天 - 选择时间点还未到涉夜加班结束时间将自动移至下一天
  DateTime finishTime = DateTime.parse(ctx.state.model.finishTime);

  TimeOfDay dayTime = TimeOfDay(hour: finishTime.hour,minute: finishTime.minute);

  TimeOfDay timeSelected = await showTimePicker(context: ctx.context, initialTime: dayTime);

  if (timeSelected == null) return;

  String timeSelectedString = timeSelected.toString();
  if (timeSelectedString.contains("TimeOfDay")) {

    timeSelectedString = timeSelectedString.substring("TimeOfDay".length + 1,"TimeOfDay".length + 6);
  }

  String newFinishTimeString = ctx.state.model.dateTime + " " + timeSelectedString + ":00";

  //所在月设置信息
  PunchCardSettingModel monthModel = await PunchCardSettingModel().getModel(ctx.state.model.monthTime);

  String monthFinishNextDayTime = ctx.state.model.dateTime + monthModel.finishNextDayTime.substring(10);
  if (DateTime.parse(newFinishTimeString).isBefore(DateTime.parse(monthFinishNextDayTime))) {

    newFinishTimeString = PunchCardModel().timeString(DateTime.parse(newFinishTimeString).add(Duration(days: 1)));
  }

  ctx.dispatch(punch_cardActionCreator.sureTimePickerAction(newFinishTimeString));
}

//刷新统计数据 - 平均下班时间
void monthTotalInfo(Context<punch_cardState> ctx) async {

  PunchCardSettingModel monthModel = await PunchCardSettingModel().getModel(ctx.state.model.monthTime);

  List<PunchCardModel> monthList = await PunchCardSettingModel().monthDatas(monthModel);

  ctx.state.monthmodel = monthModel;
  ctx.state.monthList = monthList;

  if (monthList == null) return ;
  int total = 0;
  int dayCount = 0;
  for (PunchCardModel dayModel in monthList) {

    if (dayModel.inCount) {

      Duration duration = DateTime.parse(dayModel.finishTime).difference(DateTime.parse(dayModel.dateTime + monthModel.finishTime.substring(10)));

      total += duration.inMinutes;
      dayCount += 1;
    }
  }
  if (total <= 0 || dayCount <= 0) {
    ctx.state.alreadyfinishTime = monthModel.finishTime.substring(11,16);
  } else {//设定的下班时间 + 总时间/统计天数
    ctx.state.alreadyfinishTime = DateTime.parse(monthModel.finishTime).add(Duration(minutes:(total/dayCount).floor())).toString().substring(11,16);
  }

  //刷新页面展示
  ctx.dispatch(punch_cardActionCreator.refreshMonthInfo());
}

//下班 提交操作
void _punchCardAction(fish.Action action, Context<punch_cardState> ctx) {

  List<String> tomorrowThings = ctx.state.tomorrowControllers.map((controller) => controller.text).toList();
  //保存到下一个编写日使用
  PunchCardModel().saveTomorrowThings(tomorrowThings);

  PunchCardModel storeModel = PunchCardModel(
    yearTime: ctx.state.model.yearTime,
    monthTime: ctx.state.model.monthTime,
    dateTime: ctx.state.model.dateTime,
    todayThings: ctx.state.model.todayThings,
    finishTime: ctx.state.model.finishTime,
    workingThings: ctx.state.controller.text,//填充当天内容
    tomorrowThings: tomorrowThings,//填充内容
    inCount:ctx.state.model.inCount,
  );

  PunchCardModel().save(storeModel,ctx.state.isChange);


  Duration duration = DateTime.parse(storeModel.finishTime).difference(DateTime.parse(storeModel.dateTime + "2019-09-01 17:30:00".substring(10)));

  int difHour = duration.inHours;

  String tipString = "快活啊,反正有大把时光~";
  Color timeColor = Colors.black45;
  if (difHour <= 0) {//0-1准点下班

    timeColor = Colors.orange;
    tipString = "来啊,快活啊,反正有大把时光~";
  } else if (difHour <= 2) {//2-3小时，还可以

    timeColor = Colors.green;
    List<String> list = ["也许,还能撸个串？","吼吼吼，下班下班","快,扶我起来我还能加班","安排！","养生,美滋滋~","还有谁！","嘿嘿嘿~","各位，先走为敬"];
    tipString = list[duration.inMinutes%7];
  } else if (difHour <= 4) {//4-5小时，黄线

    timeColor = Colors.yellow;
    tipString = "早点回去洗洗睡~";
  } else if (difHour <= 5) {//5-6小时，红线

    timeColor = Colors.red;
    tipString = "辛苦了,早点休息。";
  } else {//>6小时，死亡芭比粉~

    timeColor = Colors.pink;
    tipString = "如果再给我一次机会,我要早点下班！";
  }

  showDialog<Null>(
    context: ctx.context,
    barrierDismissible: true,
    builder: (BuildContext context) {
      return new AlertDialog(
        title: Row(
          children: <Widget>[
            Icon(Icons.check_circle_outline,color: Colors.blue,),
            SizedBox(width: 5,),
            new Text(storeModel.dateTime,
              style: TextStyle(color: Colors.black87,fontSize: 18,fontWeight: FontWeight.w700),
            )
          ],
        ),
        content: new SingleChildScrollView(
          child: new ListBody(
            children: <Widget>[
              new Text(storeModel.finishTime,
                style: TextStyle(color: timeColor,fontSize: 21,fontWeight: FontWeight.w300),
              ),
              SizedBox(height: 10,),
              new RichText(text: TextSpan(
                  text: tipString,
                  style: TextStyle(color: Colors.black54,fontSize: 16,fontWeight: FontWeight.w200),
              ),),
            ],
          ),
        ),
      );
    },
  );

  //更新一下页面
  ctx.dispatch(punch_cardActionCreator.restartTodayAction({"isToday":true,"isChange":true,"model":storeModel}));
}

//跳转月度设置页面
void _pushSettingVC(fish.Action action, Context<punch_cardState> ctx) {

  AppNavigator.push(ctx.context, setting.punch_card_settingPage().buildPage({"monthTime":ctx.state.model.monthTime}));
}

//跳转当月数据页面
void _pushListVC(fish.Action action, Context<punch_cardState> ctx) {

  AppNavigator.push(ctx.context, list.punch_card_listPage().buildPage({"monthList":ctx.state.monthList,"model":ctx.state.monthmodel}));
}

//切换主页
void _changeFirstPage(fish.Action action, Context<punch_cardState> ctx) {

  SNAccount().save(SNAccount.instance.account, SNAccount.instance.password, true);
}